/*
 * Description: Flip动画
 * Author: wangyifei
 * DateCreated: 2024-01-03 17:35
 */

import { useEffect, useRef } from 'react';
import { Button, Divider } from 'antd';
import { FlipStyle } from './style';

const FlipTest = () => {
	const eleRef = useRef<HTMLLIElement>();
	const ulRef = useRef<HTMLUListElement>();

	const startRef = useRef<number>(0);

	// 获取dom离顶端的距离
	function getLocation() {
		const rect = eleRef.current.getBoundingClientRect();
		return rect.top;
	}

	function raf(callback: () => void) {
		requestAnimationFrame(() => {
			requestAnimationFrame(callback);
		});
	}

	useEffect(() => {
		if (eleRef.current) {
			startRef.current = getLocation();
		}
	}, []);

	const handleMove = () => {
		ulRef.current.insertBefore(eleRef.current, null);
		const end = getLocation();
		console.log('last: ', end);

		const dis = startRef.current - end;
		eleRef.current.style.transform = `translateY(${dis}px)`;

		raf(() => {
			eleRef.current.style.transition = 'transform 1s';
			eleRef.current.style.removeProperty('transform');
		});
	};

	return (
		<FlipStyle>
			<Button type="primary" onClick={handleMove}>
				move
			</Button>
			<Divider />
			<ul className="content" ref={ulRef}>
				<li
					className="list-item"
					ref={eleRef}
					style={{ background: '#e75723', borderColor: 'red' }}
				>
					HTML + CSS
				</li>
				<li className="list-item">网络</li>
				<li className="list-item">工程化</li>
				<li className="list-item">框架</li>
				<li className="list-item">NodeJS</li>
			</ul>
		</FlipStyle>
	);
};

export default FlipTest;
